import axios from "axios";
import { message } from "antd";
import Router from "next/router";
import { removeCookie } from "@/utils/catch";
import { initialUserInfoAction } from "@/redux/actions";

import getStore from "@/redux/store";

const service = axios.create({
  baseURL: "/api/v1",
  // baseURL:
  //   process.env.NODE_ENV === "production"
  //     ? "http://49.235.175.45/blogapi/api/"
  //     : "http://localhost:4000/api",
});

service.interceptors.request.use(
  (config) => {
    let formData;
    const { data, method } = config;
    if (method === "post") {
      formData = new FormData();
      for (let key in data) {
        formData.append(key, data[key]);
      }
      config.data = formData;
    }
    return config;
  },
  (err) => {
    console.log("请求发出错误");
  }
);

service.interceptors.response.use(
  (res) => {
    if (res?.status == 200 && res.data.code != 200) {
      switch (res.data.code) {
        case 1:
          // typeof window !== "undefined" && message.error("请先登陆");
          // removeCookie();
          // typeof window !== "undefined" && Router.replace("/signin");
          return Promise.reject("请先扽登陆！");
        case -1:
          typeof window !== "undefined" && message.error("系统异常");
          return Promise.reject();
        case 406:
          typeof window !== "undefined" && message.error("图形验证码错误！");
          return Promise.reject();
        case 100:
          typeof window !== "undefined" && message.error("请先发送验证码！");
          return Promise.reject();
        case 102:
          typeof window !== "undefined" && message.error("验证码错误！");
          return Promise.reject(res.data.data);
        case 4:
          // 状态码冲突，进入下一层处理
          return Promise.reject(4);
        case 2:
          typeof window !== "undefined" &&
            message.error("该账号已被注册或绑定");
          return Promise.reject();
        case 3:
          typeof window !== "undefined" &&
            message.error("操作频繁，请2小时后再试");
          return Promise.reject();
        default:
          typeof window !== "undefined" && message.error("其他消息");
          return Promise.reject();
      }
    }
    const data = res.data?.data;
    return Promise.resolve(data);
  },
  (err) => {
    if (err && err.response && err.response.status) {
      const status = err.response.status;

      switch (status) {
        case 504:
        case 404:
          typeof window !== "undefined" && message.error("服务器异常");
          break;

        case 403:
          typeof window !== "undefined" && message.warn("访客无权进行该操作");
          break;

        case 401:
          typeof window !== "undefined" && message.info("请重新登录");
          Router.push("/login");
          break;

        default:
          typeof window !== "undefined" &&
            message.error(
              (err.response && err.response.data && err.response.data.msg) ||
                "未知错误!"
            );
      }
    }

    return Promise.reject(err);
  }
);

export default service;
